import asyncio
import json
import socket
import time
import datetime
#import psutil
import random
ipaddr = socket.gethostbyname(socket.getfqdn(socket.gethostname()))

async def tcp_echo_client(message, host, port):
    reader, writer = await asyncio.open_connection(host, port)

    print(f"Send: {message}")
    writer.write(message.encode('utf-8'))
    await writer.drain()

    data = await reader.read(1024)
    print(f"Received: {data.decode('utf-8')}")

    print("Close the connection")
    writer.close()

loop = asyncio.get_event_loop()
while 1:
    # 获取CPU使用率，并以百分比格式返回
    #cpu_percent = psutil.cpu_percent(interval=1)
    cpu_percent = random.randint(50,100)
    message = {
        "event": "performance",
        "data": {
            "logtime": datetime.datetime.now().strftime("%H:%M:%S"),
            "host": ipaddr,
            "cpu": str(cpu_percent)
        }
    }
    loop.run_until_complete(tcp_echo_client(json.dumps(message), '127.0.0.1', 8888))
    time.sleep(10)

#"logtime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),